package com.example.leetcode.leetcode;


import java.util.*;

class Solution347 {
    //347. 前 K 个高频元素
    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> numsCount = new HashMap<>(16);
        for(int i=0;i<nums.length;i++){
            if(null!=numsCount.get(nums[i])){
                numsCount.put(nums[i],numsCount.get(nums[i])+1);
            }else{
                numsCount.put(nums[i],1);
            }
        }
        //通过value进行排序
        List <Map.Entry<Integer,Integer>> list = new ArrayList<>(numsCount.entrySet());
        Collections.sort(list, (o1, o2) -> o2.getValue()-o1.getValue());
        int [] res=new int[k];
        for (int i = 0; i <k ; i++) {
            res[i]=list.get(i).getKey();
        }
        return res;
    }

    public static void main(String[] args) {
        int [] nums={1,1,1,2,2,3};
        int k = 2;
        System.out.println(Arrays.toString(topKFrequent(nums, k)));
    }
}